//
//  XiaoximenMainViewController.m
//  Xiaoximen_iOS
//
//  Created by Wang Zhongyu on 12-7-17.
//  Copyright (c) 2012年 Peking University. All rights reserved.
//

#import "XiaoximenMainViewController.h"
#import "XiaoximenVoteBasicInfoViewController.h"
#import "XiaoximenResultViewController.h"
#import "XiaoximenAppDelegate.h"
#import "ASIHTTPRequest.h"

@interface XiaoximenMainViewController () {
	// Single Party Request
	NSDictionary *newParty;
	NSArray *newTimes;
	NSArray *newPlaces;
	NSArray *newTimeResults;
	NSArray *newPlaceResults;
	ASIHTTPRequest *requestParty;
	ASIHTTPRequest *requestTimes;
	ASIHTTPRequest *requestPlaces;
	ASIHTTPRequest *requestPlaceResults;
	ASIHTTPRequest *requestTimeResults;
	int completeNumber;
	
	// All Parties
	NSArray *newPartyIDs;
	int nowIndex;
	BOOL bRequest;
	
	NSString *nextSegueIdentifier;
}

@end

@implementation XiaoximenMainViewController
@synthesize subview;
@synthesize parties = _parties;
@synthesize invitationsDownloaded = _invitationsDownloaded;
@synthesize invitationsLoaded = _invitationsLoaded;
@synthesize delegate;
@synthesize progressHub;

- (NSObject<PABezelHUDDelegate> *)delegate {
    if (delegate == nil) {
        delegate = (NSObject<PABezelHUDDelegate> *)[UIApplication sharedApplication].delegate;
    }
    return delegate;
}
- (MBProgressHUD *)progressHub{
    if (progressHub == nil) {
        progressHub = self.delegate.progressHub;
    }
    return progressHub;
}
- (void)showProgressHubWithTitle:(NSString *)title{
    self.progressHub.mode = MBProgressHUDModeIndeterminate;
    self.progressHub.delegate = self;
    self.progressHub.labelText = title;
    [self.progressHub show:YES];
}
- (void)changeProgressHub:(NSString *)title
{
	progressHub.animationType = MBProgressHUDAnimationZoom;
    self.progressHub.labelText = title;
    self.progressHub.mode = MBProgressHUDModeCustomView;
    [self.progressHub hide:YES afterDelay:1];
}
- (NSMutableDictionary *)invitationsDownloaded
{
	if (_invitationsDownloaded == nil) {
		_invitationsDownloaded = [[[NSUserDefaults standardUserDefaults] valueForKey:kINVITATIONIDDOWNLOADED] mutableCopy];
	}
	if (_invitationsDownloaded == nil) {
		_invitationsDownloaded = [[NSMutableDictionary alloc] init];
	}
	return _invitationsDownloaded;
}
- (NSMutableDictionary *)invitationsLoaded
{
	if (_invitationsLoaded == nil) {
		_invitationsLoaded = [[NSMutableDictionary alloc] init];
	}
	return _invitationsLoaded;
}
- (NSMutableArray *)parties
{
	if (_parties == nil) {
		_parties = [[[XiaoximenParty class] demoParties] mutableCopy];
		[self addMyInfo];
	}
	return _parties;
}

- (IBAction)onCreateParty:(id)sender {
	if (bRequest) return ;
	[self performSegueWithIdentifier:@"CreatePartySegue" sender:self];
}

- (IBAction)onVoteParty:(id)sender {
	if (bRequest) return ;
	NSMutableArray *invitationIDs = [[NSUserDefaults standardUserDefaults] objectForKey:kINVITATIONIDS];
	nextSegueIdentifier = @"VotePartySegue";
	[self requestParties:invitationIDs];
}

- (IBAction)onResultParty:(id)sender {
	if (bRequest) return ;
	NSMutableArray *invitationIDs = [[NSUserDefaults standardUserDefaults] objectForKey:kINVITATIONIDS];
	nextSegueIdentifier = @"ResultSegue";
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:kINVITATIONIDDOWNLOADED];
	[self requestParties:invitationIDs];
}
- (void)addMyInfo
{
	NSString *myName = [[NSUserDefaults standardUserDefaults] valueForKey:kNAME];
	int myID = [[[NSUserDefaults standardUserDefaults] valueForKey:kID] intValue];
	for (XiaoximenParty *party in self.parties) {
		[party addPersonWithPhoneString:nil userName:myName personID:myID];
	}
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	[self.view setBackgroundColor:[UIColor colorWithRed:197/255.0 green:234/255.0 blue:248/255.0 alpha:1.0]];
	[self.subview setBackgroundColor:[UIColor colorWithRed:226/255.0 green:244/255.0 blue:251/255.0 alpha:1.0]];
#warning 演示版本增加第一个投票
	NSMutableArray *invitationIDs = [[[NSUserDefaults standardUserDefaults] objectForKey:kINVITATIONIDS] mutableCopy];
	if (invitationIDs == nil) invitationIDs = [[NSMutableArray alloc] init];
	if (![invitationIDs containsObject:[NSString stringWithFormat:@"%d", 1]]) [invitationIDs addObject:[NSString stringWithFormat:@"%d", 1]];
	[[NSUserDefaults standardUserDefaults] setObject:invitationIDs forKey:kINVITATIONIDS];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:kINVITATIONIDDOWNLOADED];
}

- (void)viewDidUnload
{
	[self setSubview:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];
#warning 服务器挂了，所以暂时不需要登录
//	if (![[NSUserDefaults standardUserDefaults] valueForKey:@"user_name"]) {
//		[self performSegueWithIdentifier:@"LoginSegue" sender:self];
//	}
}

- (void)addNewPartyInfo:(NSUInteger)partyID;
{
	if (![[self.invitationsDownloaded objectForKey:[NSString stringWithFormat:@"%d", partyID]] isEqualToString:@"YES"] || ![[self.invitationsLoaded objectForKey:[NSString stringWithFormat:@"%d", partyID]] isEqualToString:@"YES"]) {
		
		[self.invitationsDownloaded setObject:@"YES" forKey:[NSString stringWithFormat:@"%d", partyID]];
		[[NSUserDefaults standardUserDefaults] setObject:self.invitationsDownloaded forKey:kINVITATIONIDDOWNLOADED];
		self.invitationsDownloaded = nil;
		[self.invitationsLoaded setValue:@"YES" forKey:[NSString stringWithFormat:@"%d", partyID]];
	
		int waitToAddPartyID = partyID;
		newParty = [[NSUserDefaults standardUserDefaults] objectForKey:[kNEWPARTY stringByAppendingFormat:@"%d", partyID]];
		newPlaces = [[NSUserDefaults standardUserDefaults] objectForKey:[kNEWPLACES stringByAppendingFormat:@"%d", partyID]];
		newTimes = [[NSUserDefaults standardUserDefaults] objectForKey:[kNEWTIMES stringByAppendingFormat:@"%d", partyID]];
		newPlaceResults = [[NSUserDefaults standardUserDefaults] objectForKey:[kNEWPLACERESULTS stringByAppendingFormat:@"%d", partyID]];
		newTimeResults = [[NSUserDefaults standardUserDefaults] objectForKey:[kNEWTIMERESULTS stringByAppendingFormat:@"%d", partyID]];
		
		XiaoximenParty *addedParty = [[XiaoximenParty alloc] initWithHostName:[[newParty objectForKey:@"inviter"] objectForKey:@"name"] themeTitle:[newParty objectForKey:@"title"] partyID:waitToAddPartyID];
		
		int i;
		for (i = 0; i < self.parties.count; i++) {
			if ([[self.parties objectAtIndex:i] ID] == waitToAddPartyID) {
				[self.parties removeObjectAtIndex:i];
			}
		}
		[self.parties addObject:addedParty];
		
		for (NSDictionary *placeDict in newPlaces) {
			[addedParty addPlaceWithPlaceName:[placeDict objectForKey:kPLACENAME] placeID:[[placeDict objectForKey:kPLACEID] intValue]];
		}
		for (NSDictionary *timeDict in newTimes) {
			[addedParty addTimeWithStartDate:[NSDate dateWithTimeIntervalSince1970:[[timeDict objectForKey:kTIMESTART] intValue]] endDate:[NSDate dateWithTimeIntervalSince1970:[[timeDict objectForKey:kTIMEEND] intValue]] timeID:[[timeDict objectForKey:kTIMEID] intValue]];
		}
		
		for (NSDictionary *placeResultDict in newPlaceResults) {
			[addedParty addPersonWithPhoneString:nil userName:[placeResultDict objectForKey:kRESULTNAME] personID:[[placeResultDict objectForKey:kRESULTID] intValue]];
			XiaoximenPerson *person = [addedParty.persons lastObject];
			for (NSDictionary *resultDict in [placeResultDict objectForKey:kRESULT]) {
				if ([[resultDict objectForKey:@"checked"] boolValue]) {
					[person yesForPlaceID:[[resultDict objectForKey:@"option_id"] intValue]];
				} else {
					[person noForPlaceID:[[resultDict objectForKey:@"option_id"] intValue]];
				}
			}
		}
		for (NSDictionary *timeResultDict in newTimeResults) {
			for (XiaoximenPerson *person in addedParty.persons) {
				if (person.ID != [[timeResultDict objectForKey:kRESULTID] intValue]) continue;
				for (NSDictionary *resultDict in [timeResultDict objectForKey:kRESULT]) {
					if ([[resultDict objectForKey:@"checked"] boolValue]) {
						[person yesForTimeID:[[resultDict objectForKey:@"option_id"] intValue]];
					} else {
						[person noForTimeID:[[resultDict objectForKey:@"option_id"] intValue]];
					}
				}
			}
		}
	}
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	
	UINavigationController *nc = segue.destinationViewController;
	if ([segue.identifier isEqualToString:@"VotePartySegue"]) {
		XiaoximenVoteBasicInfoViewController *vbivc = (XiaoximenVoteBasicInfoViewController *)(nc.topViewController);
		vbivc.parties = self.parties;
	} else if ([segue.identifier isEqualToString:@"ResultSegue"]) {
		XiaoximenResultViewController *rvc = (XiaoximenResultViewController *)(nc.topViewController);
		rvc.parties = self.parties;
	}
}

- (void)notifyWithUrl:(NSString *)urlString
{
	int partyID = 1;
	if ([urlString hasPrefix:@"xiaoximen://invitation/"]) {
		partyID =  [[urlString substringFromIndex:[@"xiaoximen://invitation/" length]] intValue];
	}
	if (partyID == 0) {
		[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
		return;
	}
	
	NSMutableArray *invitationIDs = [[[NSUserDefaults standardUserDefaults] objectForKey:kINVITATIONIDS] mutableCopy];
	if (invitationIDs == nil) invitationIDs = [[NSMutableArray alloc] init];
	if (![invitationIDs containsObject:[NSString stringWithFormat:@"%d", partyID]]) [invitationIDs addObject:[NSString stringWithFormat:@"%d", partyID]];
	[[NSUserDefaults standardUserDefaults] setObject:invitationIDs forKey:kINVITATIONIDS];
	
	nextSegueIdentifier = @"VotePartySegue";
	[self requestParties:invitationIDs];	
}

- (void)requestParties:(NSArray *)partyIDs
{
	if (!partyIDs.count) {
		[self performSegueWithIdentifier:nextSegueIdentifier sender:self];
		return ;
	}
	[self showProgressHubWithTitle:@"更新中...先别点哦^_^"];
	bRequest = YES;
	newPartyIDs = [[NSArray alloc] initWithArray:partyIDs];
	[self requestNewParty:0];
}
- (void)requestNextNewParty
{
	int partyID = [[newPartyIDs objectAtIndex:nowIndex] intValue];
	[self addNewPartyInfo:partyID];
	
	nowIndex++;
	if (nowIndex < newPartyIDs.count) [self requestNewParty:nowIndex];
	else {
		[self changeProgressHub:@"更新成功！"];
		bRequest = NO;
		[self performSegueWithIdentifier:nextSegueIdentifier sender:self];
	}
}
- (void)requestNewParty:(int)index
{
	nowIndex = index;
	int partyID = [[newPartyIDs objectAtIndex:index] intValue];
	if ([[self.invitationsDownloaded objectForKey:[NSString stringWithFormat:@"%d", partyID]] isEqualToString:@"YES"]) {
		self.invitationsDownloaded = nil;
		[self requestNextNewParty];
		return ;
	} else {
		self.invitationsDownloaded = nil;
		id navCtrl = [self presentedViewController];
		if ([navCtrl isKindOfClass:[UINavigationController class]]) {
			[((UINavigationController *)navCtrl).visibleViewController dismissModalViewControllerAnimated:YES];
		} else {
			[navCtrl dismissModalViewControllerAnimated:YES];
		}
	}
	
	[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d", partyID] forKey:kNEWPARTYID];
	completeNumber = 0;
	
	NSURL *urlParty = [NSURL URLWithString:
					   [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/detail", partyID]];
	requestParty = [ASIHTTPRequest requestWithURL:urlParty];
	[requestParty setDelegate:self];
	[requestParty setTimeOutSeconds:20];
	[requestParty startAsynchronous];
	
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];
	int partyID = [[[NSUserDefaults standardUserDefaults] objectForKey:kNEWPARTYID] intValue];
	id res = [NSJSONSerialization JSONObjectWithData:responseData
											 options:NSJSONWritingPrettyPrinted
											   error:nil];
	if ([res isKindOfClass:[NSDictionary class]] && [res objectForKey:@"error"]) {
		[self changeProgressHub:@"数据更新失败><"];
		bRequest = NO;
		[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
		return ;
	}
	
	if ([request isEqual:requestParty]) {
		newParty = [NSJSONSerialization JSONObjectWithData:responseData
													  options:NSJSONWritingPrettyPrinted
														error:nil];
		NSLog(@"%@", newParty);
		completeNumber++;
		[[NSUserDefaults standardUserDefaults] setObject:newParty forKey:[kNEWPARTY stringByAppendingFormat:@"%d", partyID]];
		
		NSURL *urlPlaces = [NSURL URLWithString:
							[NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/option/place", partyID]];
		requestPlaces = [ASIHTTPRequest requestWithURL:urlPlaces];
		[requestPlaces setDelegate:self];
		[requestPlaces setTimeOutSeconds:20];
		[requestPlaces startAsynchronous];
		
	} else if ([request isEqual:requestPlaces]) {
		newPlaces = [NSJSONSerialization JSONObjectWithData:responseData
													  options:NSJSONWritingPrettyPrinted
														error:nil];
		NSLog(@"%@", newPlaces);
		completeNumber++;
		[[NSUserDefaults standardUserDefaults] setObject:newPlaces forKey:[kNEWPLACES stringByAppendingFormat:@"%d", partyID]];
		
		NSURL *urlTimes = [NSURL URLWithString:
						   [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/option/time", partyID]];
		requestTimes = [ASIHTTPRequest requestWithURL:urlTimes];
		[requestTimes setDelegate:self];
		[requestTimes setTimeOutSeconds:20];
		[requestTimes startAsynchronous];
		
	} else if ([request isEqual:requestTimes]) {
		newTimes = [NSJSONSerialization JSONObjectWithData:responseData
													  options:NSJSONWritingPrettyPrinted
														error:nil];
		NSLog(@"%@", newTimes);
		completeNumber++;
		[[NSUserDefaults standardUserDefaults] setObject:newTimes forKey:[kNEWTIMES stringByAppendingFormat:@"%d", partyID]];
		
		NSURL *urlPlaceResults = [NSURL URLWithString:
								  [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/result/place", partyID]];
		requestPlaceResults = [ASIHTTPRequest requestWithURL:urlPlaceResults];
		[requestPlaceResults setDelegate:self];
		[requestPlaceResults setTimeOutSeconds:20];
		[requestPlaceResults startAsynchronous];
		
	} else if ([request isEqual:requestPlaceResults]) {
		newPlaceResults = [NSJSONSerialization JSONObjectWithData:responseData
												   options:NSJSONWritingPrettyPrinted
													 error:nil];
		NSLog(@"%@", newPlaceResults);
		completeNumber++;
		[[NSUserDefaults standardUserDefaults] setObject:newPlaceResults forKey:[kNEWPLACERESULTS stringByAppendingFormat:@"%d", partyID]];
		
		NSURL *urlTimeResults = [NSURL URLWithString:
								 [NSString stringWithFormat:@"http://xiaoximen.pkuapp.com/invitation/%d/result/time", partyID]];
		requestTimeResults = [ASIHTTPRequest requestWithURL:urlTimeResults];
		[requestTimeResults setDelegate:self];
		[requestTimeResults setTimeOutSeconds:20];
		[requestTimeResults startAsynchronous];

	} else if ([request isEqual:requestTimeResults]) {
		newTimeResults = [NSJSONSerialization JSONObjectWithData:responseData
												   options:NSJSONWritingPrettyPrinted
													 error:nil];
		NSLog(@"%@", newTimeResults);
		completeNumber++;
		[[NSUserDefaults standardUserDefaults] setObject:newTimeResults forKey:[kNEWTIMERESULTS stringByAppendingFormat:@"%d", partyID]];
	}
	
	if (completeNumber == 5) [self requestNextNewParty];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	NSError *error = [request error];
	NSLog(@"%@", error);
	[self changeProgressHub:@"数据更新失败><"];
	bRequest = NO;
	[self performSegueWithIdentifier:@"ErrorSegue" sender:self];
}

@end
